//
//  HomeViewController.m
//  Blue-toothLight
//
//  Created by mazg on 15/6/17.
//  Copyright (c) 2015年 mazg. All rights reserved.
//

#import "HomeViewController.h"
#import "OperationBlueTooth.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "LightModel.h"
#import "NSManagedObject+helper.h"
#import "LightTabViewController.h"
#import "OperationColor.h"

#import "GroupViewController.h"

#define WinWidth [UIScreen mainScreen].bounds.size.width
#define WinHeight [UIScreen mainScreen].bounds.size.height

#define W(x) WinWidth*x/320.0
#define H(y) WinHeight*y/568.0

@interface HomeViewController ()<OperationBlueToothDelegate,UITextFieldDelegate>{
    OperationColor *colorInstance;
}

@property(nonatomic,strong)CBPeripheral *selectedPer;
@property(nonatomic,strong)LightModel *selectedModel;

@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    colorInstance=[OperationColor shareOperationColorInstance];
    [self setUpUI];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //指定蓝牙模块代理，刷新tableview
    OperationBlueTooth *tooth=[OperationBlueTooth shareOperationBlueToothInsatnce];
    tooth.delegate=self;
    [self reloadLightTableViewData];
}

-(void)setUpUI{
//1、显示搜索列表的tableview
    self.tableView=[[UITableView alloc]init];
    self.tableView.frame=CGRectMake(0, WinHeight, WinWidth, H(350));
    self.tableView.alpha=0.6;
    self.tableView.backgroundColor=[UIColor blackColor];
    [self.view addSubview:self.tableView];
    
    self.tableView.dataSource=self;
    self.tableView.delegate=self;
    self.tableView.rowHeight=60;
    
    self.isShowTableView=NO;
    
//2、设置灯的名字的视图
    self.setView.hidden=YES;
    
//3、显示所有可以操作的灯的tableView
    self.lightTableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    self.lightTableView.rowHeight=60;
    self.lightTableView.backgroundColor=[UIColor clearColor];
}

-(NSMutableArray *)perForShowArr{
    if (!_perForShowArr) {
        _perForShowArr=[[NSMutableArray alloc]init];
    }
    return _perForShowArr;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//设置灯的名字
- (IBAction)setLightName:(id)sender {
    [self.view endEditing:YES];
    self.setView.hidden=YES;
    //如果长按cell，选择了对应的灯进行修改
    if (self.selectedModel) {
        self.selectedModel.roomName=self.lightNameTextfield.text;
        [LightModel save:^(NSError *error) {
            
        }];
        self.selectedModel=nil;
    }
    //如果第一次设置这个灯的信息
    else{
        //1、对选中灯做入库操作
        NSArray *dataBaseArr=[LightModel filter:nil orderby:nil offset:0 limit:0];
        BOOL isExiseInDataBase=NO;
        for (LightModel *tmpModel in dataBaseArr) {
            if ([tmpModel.perIdentifier isEqualToString:_selectedPer.identifier.UUIDString]) {
                isExiseInDataBase=YES;
            }
        }
        if (!isExiseInDataBase) {
            LightModel *model=[LightModel createNew];
            model.perName=_selectedPer.name;
            model.perIdentifier=_selectedPer.identifier.UUIDString;
            model.groupName=nil;
            model.roomName=self.lightNameTextfield.text;
            model.isExist=@YES;
            model.isConnected=@NO;
            model.perColor=[UIColor colorWithRed:80/255.0f green:0/255.0f blue:0/255.0f alpha:0.0];
            model.isOpen=@NO;
        }
        else{
            self.selectedModel.roomName=self.lightNameTextfield.text;
        }
        [LightModel save:^(NSError *error) {
            
        }];
        //2、蓝牙连接操作
        [[OperationBlueTooth shareOperationBlueToothInsatnce].cbCentralMgr connectPeripheral:_selectedPer options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey]];
        self.selectedPer=nil;
    }
    
    //3、界面显示操作
    [self reloadLightTableViewData];
    [self.perForShowArr removeObject:_selectedPer];
    [self.tableView reloadData];
}

- (IBAction)showGroup:(id)sender {
    
}

//从蓝牙列表中添加一个灯
- (IBAction)addLight:(id)sender {
    self.isShowTableView=!self.isShowTableView;
    if (self.isShowTableView) {
        [UIView animateWithDuration:0.5 animations:^{
            self.tableView.frame=CGRectMake(0, WinHeight-H(350), WinWidth, H(350));
        }];
    }
    else{
        [UIView animateWithDuration:0.5 animations:^{
            self.tableView.frame=CGRectMake(0, WinHeight, WinWidth, H(350));
        }];
    }
}

//所有的灯开关
- (IBAction)toggleSwitch:(id)sender {
    
    if (self.allConnectedPerArr.count==0) {
        return;
    }
    
    UIButton *btn=sender;
    btn.selected=!btn.selected;
    
    for (LightModel *model in self.lightTableViewList) {
        if (model.isConnected) {
            for (CBPeripheral *cbp in self.allConnectedPerArr) {
                if ([cbp.identifier.UUIDString isEqualToString:model.perIdentifier]) {
                    if ([model.isOpen boolValue]) {
                        [colorInstance turnOffLightWithPeripheral:cbp];
                    }
                    else{
                        [colorInstance openLightWithPeripheral:cbp];
                    }
                }
            }
        }
    }
}


//cell中灯的开关
- (IBAction)toggleCellSwitch:(id)sender {
    UITableViewCell *cell=(UITableViewCell *)[sender superview].superview;
    NSIndexPath *path=[self.lightTableView indexPathForCell:cell];
    LightModel *model=self.lightTableViewList[path.row];
    
    for (CBPeripheral *cbp in self.allConnectedPerArr) {
        if ([cbp.identifier.UUIDString isEqualToString:model.perIdentifier]) {
            if ([model.isOpen boolValue]) {
                [colorInstance turnOffLightWithPeripheral:cbp];
            }
            else{
                [colorInstance openLightWithPeripheral:cbp];
            }
        }
    }
}




-(void)reloadLightTableViewData{
    self.lightTableViewList=[[LightModel filter:nil orderby:nil offset:0 limit:0] mutableCopy];
    [self.lightTableView reloadData];
}


//cell中的长按手势方法
-(void)longGestureAction:(UILongPressGestureRecognizer *)ges{
    if (ges.state == UIGestureRecognizerStateBegan) {
        UITableViewCell *cell=(UITableViewCell *)ges.view;
        NSIndexPath *path=[self.lightTableView indexPathForCell:cell];
        LightModel *model=self.lightTableViewList[path.row];
        self.lightNameTextfield.text=model.perName;
        self.selectedModel=model;
        self.setView.hidden=NO;
    }
}


#pragma mark OperationBlueToothDelegate
-(void)reloadTableViewDataWithAllPer:(NSMutableArray *)allPer andConnectedPer:(NSMutableArray *)connectedPer{
    //1、清空数据，初始化数组
    [self.perForShowArr removeAllObjects];
    self.allPerArr=allPer;
    self.allConnectedPerArr=connectedPer;
    
    
//    NSLog(@"++++++++++++++++++++++++++%@",self.allPerArr);
    
    //2、当前tableview的数据源只需要显示所有没有连接的外围设备
    for (CBPeripheral *per in allPer) {
        if (per.state==CBPeripheralStateDisconnected) {
            //如果这个设备已经存在数据库中，就不需要再搜索列表中显示了，并且同时连接该设备
            BOOL isExistInDataBase=NO;
            for (LightModel *model in self.lightTableViewList) {
                if ([model.perIdentifier isEqualToString:per.identifier.UUIDString]) {
                    isExistInDataBase=YES;
                    [[OperationBlueTooth shareOperationBlueToothInsatnce].cbCentralMgr connectPeripheral:per options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey]];
                    
                }
            }
            if (isExistInDataBase==NO) {
                [self.perForShowArr addObject:per];
                [self.tableView reloadData];
            }
        }
    }
    [self.lightTableView reloadData];
    [self.delegate changeDataWithAllPer:self.allPerArr andConnectedPer:self.allConnectedPerArr];
}



#pragma mark UITableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([tableView isEqual:_tableView]) {
        return self.perForShowArr.count;
    }
    else{
        return self.lightTableViewList.count;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:_tableView]) {
        static NSString *identifier=@"cell";
        UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell==nil) {
            cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            cell.backgroundColor=[UIColor clearColor];
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
        }
        cell.textLabel.textColor=[UIColor whiteColor];
        CBPeripheral *per=self.perForShowArr[indexPath.row];
        
        cell.textLabel.text=per.name;
        return cell;
    }
    else{
        UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell"];
        cell.backgroundColor=[UIColor clearColor];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.textLabel.textColor=[UIColor whiteColor];
        cell.showsReorderControl =YES;
        
        LightModel *model=self.lightTableViewList[indexPath.row];
        cell.imageView.image=[UIImage imageNamed:@"gound_tap@2x.png"];
        cell.textLabel.text=model.roomName;
        
        UILongPressGestureRecognizer *longGesture=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longGestureAction:)];
        longGesture.minimumPressDuration=0.5;
        [cell addGestureRecognizer:longGesture];
        
        UISwitch *swc=(UISwitch *)[cell viewWithTag:100];
        swc.frame=CGRectMake(W(260), 15, 40, 30);
        swc.on=[model.isOpen boolValue];
        if (![model.isConnected boolValue]) {
            swc.enabled=NO;
        }
        else{
            swc.enabled=YES;
        }
        return cell;
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if ([tableView isEqual:_tableView]) {
        UIView *view=[[UIView alloc]init];
        UIImageView *imgView=[[UIImageView alloc]init];
        imgView.frame=CGRectMake(WinWidth/2.0f-25, 0, 50, 30);
        imgView.image=[UIImage imageNamed:@"snsmore.png"];
        [view addSubview:imgView];
        view.userInteractionEnabled=YES;
        UITapGestureRecognizer *gesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(addLight:)];
        [view addGestureRecognizer:gesture];
        return view;
    }
    else{
        return nil;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:_tableView]) {
        return 60;
    }
    else{
        return 60;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if ([tableView isEqual:_tableView]) {
        return 30;
    }
    else{
        return 0.01;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:_tableView]) {
        
        CBPeripheral *per=self.perForShowArr[indexPath.row];
        self.selectedPer=per;
        [self addLight:nil];
        self.lightNameTextfield.text=per.name;
        self.setView.hidden=NO;
    }
    else{
    //如果灯没有连接，则不能操作
        LightModel *model=self.lightTableViewList[indexPath.row];
        if (![model.isConnected boolValue]) {
            return;
        }
        UIStoryboard *main=[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
        LightTabViewController *tabVC=[main instantiateViewControllerWithIdentifier:@"lightTab"];
        tabVC.currentLightList=@[model];
        tabVC.allConnectedPerArr=self.allConnectedPerArr;
        [self presentViewController:tabVC animated:YES completion:nil];
    }
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    //1、断开连接
    LightModel *model=self.lightTableViewList[indexPath.row];
//    NSLog(@"allConnectedPerArr===%@",self.allConnectedPerArr);
    for (CBPeripheral *cbp in self.allConnectedPerArr) {
        if ([cbp.identifier.UUIDString isEqualToString:model.perIdentifier]) {
            [[OperationBlueTooth shareOperationBlueToothInsatnce].cbCentralMgr cancelPeripheralConnection:cbp];
        }
    }
    
    //2、删除数据
    [LightModel delobject:self.lightTableViewList[indexPath.row]];
    [LightModel save:^(NSError *error) {
        
    }];
    [self.lightTableViewList removeObjectAtIndex:indexPath.row];
    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:_tableView]) {
        return NO;
    }
    else{
        return YES;
    }
}

#pragma mark UITextFieldDelegate
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    textField.text=@"";
    textField.returnKeyType=UIReturnKeyDone;
    return YES;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    [self setLightName:nil];
    return YES;
}


-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([segue.identifier isEqualToString:@"presentGroup"]) {
        GroupViewController *group=(GroupViewController *)[segue.destinationViewController topViewController];
        group.allPerArr=self.allPerArr;
        group.allConnectedPerArr=self.allPerArr;
        self.delegate=group;
    }
}


@end
